using System;
using System.Collections.Generic;
using System.Linq.Expressions;
using System.Text;
using System.Threading.Tasks;
using Npoi.Mapper;
using Publicuse.Appication;
using Publicuse.Autofac;
using Publicuse.Cache;
using Publicuse.Entity;
using Publicuse.Entity.AttributeUtil;
using Publicuse.Export;
using Publicuse.Interface;
using Publicuse.Util;

namespace Publicuse.Application
{
  /// <summary>
  /// 数据字典管理
  /// </summary>
  public class DictionariesApplication
  {
    private static BaesApplication baseApplication;
    private static DictionariesApplication userApplication;

    public static DictionariesApplication GetApplication(ServiceContainer container)
    {
      baseApplication = new BaesApplication(container);
      return userApplication;
    }

    static DictionariesApplication()
    {
      userApplication = new DictionariesApplication();
    }

    /// <summary>
    /// 获取数据三级联动信息
    /// </summary>
    /// <returns></returns>
    public async Task<CommonResult> GetTreeList()
    {
      return await Task.Factory.StartNew(() =>
      {
        CommonResult result = new CommonResult();
        var table = TableAtributeUtil.GetTable<Dictionaries>();
        var sql = $"select Id,dName,dParentcode,dValue from {table} where dTypeName='中国省市区';";
        var list = baseApplication.mySqlSugar.Query<Dictionaries>(sql, null, out var msg);
        List<DictionariesTree> dictionariesTrees = new List<DictionariesTree>();
        if (string.IsNullOrEmpty(msg) && list != null && list.Count > 0)
        {
          var provincelist = list.Where(o => o.dValue == "province");
          var citylist = list.Where(o => o.dValue == "city");
          var districtlist = list.Where(o => o.dValue == "district");
          provincelist.ForEach(item =>
          {
            DictionariesTree dictionaries = new DictionariesTree()
            {
              value = item.Id.ToString(),
              label = item.dName
            };
            var childrenlist = citylist.Where(o => o.dParentcode == item.Id.ToString());
            if (childrenlist != null && childrenlist.Count() > 0)
            {
              dictionaries.children = new List<DictionariesTree>();
              childrenlist.ForEach(itemb =>
              {
                DictionariesTree dictionariesb = new DictionariesTree()
                {
                  value = itemb.Id.ToString(),
                  label = itemb.dName
                };
                var childrenlistb = districtlist.Where(o => o.dParentcode == itemb.Id.ToString());
                if (childrenlistb != null && childrenlistb.Count() > 0)
                {
                  dictionariesb.children = new List<DictionariesTree>();
                  childrenlistb.ForEach(itemc =>
                  {
                    DictionariesTree dictionariesc = new DictionariesTree()
                    {
                      value = itemc.Id.ToString(),
                      label = itemc.dName
                    };
                    dictionariesb.children.Add(dictionariesc);
                  });
                }
                dictionaries.children.Add(dictionariesb);
              });
            }
            dictionariesTrees.Add(dictionaries);
          });
        }
        result.data = dictionariesTrees;
        return result;
      });
    }

    /// <summary>
    /// 获取数据字典详细信息
    /// </summary>
    /// <param name="Id"></param>
    /// <returns></returns>
    public async Task<CommonResult> GetDetail(int Id)
    {
      return await Task.Factory.StartNew(() =>
      {
        CommonResult result = new CommonResult();
        var list = baseApplication.mySqlSugar.QueryByExpression<Dictionaries>(
          o => o.Id == Id,
          out var msg
        );
        if (string.IsNullOrEmpty(msg) && list != null && list.Count > 0)
        {
          var spconf = list.FirstOrDefault();
          result.data = spconf;
        }
        result.msg = msg;
        return result;
      });
    }

    /// <summary>
    /// 获取数据字典信息列表
    /// </summary>
    /// <param name="query"></param>
    /// <returns></returns>
    public async Task<CommonResult> GeList(Dictionaries query)
    {
      return await Task.Factory.StartNew(() =>
      {
        CommonResult result = new CommonResult();
        var tableName = TableAtributeUtil.GetTable<Dictionaries>();
        tableName =
          $"(select a.*,b.dName as dParentName from {tableName} a left join {tableName} b on a.dParentcode=b.Id group by a.Id) as urp";
        string sql = query.GetQueryString<Dictionaries>(null);
        DictionariesQuery dictionariesQuery = new DictionariesQuery()
        {
          tableName = tableName,
          sqlWhere = sql,
          sortFile = query.sortFile,
          sortType = query.sortType,
          files = query.files,
          pageIndex = query.pageIndex,
          pageSize = query.pageSize,
        };
        result = baseApplication
          .GetList<Dictionaries>(dictionariesQuery, false)
          .GetAwaiter()
          .GetResult();
        return result;
      });
    }

    /// <summary>
    /// 检查数据字典类型编码是否存在
    /// </summary>
    /// <param name="dTypeName"></param>
    /// <param name="dCode"></param>
    /// <param name="loginUserCode"></param>
    /// <param name="Id"></param>
    /// <returns></returns>
    public async Task<CommonResult> CheckCode(
      string dTypeName,
      string dCode,
      string loginUserCode,
      string Id = ""
    )
    {
      return await baseApplication.CheckDataExists<Dictionaries>(
        BusinessType.dictionaries,
        BusinessLogType.writeLogToDataBase,
        o => o.dTypeName == dTypeName && o.dCode == dCode && o.status != -9,
        "检查数据字典类型是否存在",
        Id
      );
    }

    /// <summary>
    /// 检查数据字典类型名称是否存在
    /// </summary>
    /// <param name="dTypeName"></param>
    /// <param name="dName"></param>
    /// <param name="loginUserCode"></param>
    /// <param name="Id"></param>
    /// <returns></returns>
    public async Task<CommonResult> CheckName(
      string dTypeName,
      string dName,
      string loginUserCode,
      string Id = ""
    )
    {
      return await baseApplication.CheckDataExists<Dictionaries>(
        BusinessType.dictionaries,
        BusinessLogType.writeLogToDataBase,
        o => o.dTypeName == dTypeName && o.dName == dName && o.status != 9,
        "检查数据字典名称是否存在",
        Id
      );
    }

    /// <summary>
    /// 根据数据字典类型获取列表信息
    /// </summary>
    /// <param name="dTypeName"></param>
    /// <param name="dParentcode"></param>
    /// <returns></returns>
    public async Task<CommonResult> GetListc(string dTypeName, string dParentcode)
    {
      return await Task.Factory.StartNew(() =>
      {
        CommonResult result = new CommonResult();
        List<Dictionaries> dictionaries = new List<Dictionaries>();
        Expression<Func<Dictionaries, bool>> expression = null;
        expression = expression.And(o => o.dTypeName == dTypeName && o.status == 1);
        if (!string.IsNullOrEmpty(dParentcode))
        {
          expression = expression.And(o => o.dParentcode == dParentcode);
        }
        var list = baseApplication.mySqlSugar.QueryByExpression<Dictionaries>(
          expression,
          out var msg
        );
        if (string.IsNullOrEmpty(msg) && list != null && list.Count > 0)
        {
          dictionaries = list;
        }
        result.data = list;
        result.msg = msg;
        return result;
      });
    }

    /// <summary>
    /// 根据数据字典类型获取列表信息
    /// </summary>
    /// <param name="dTypeName"></param>
    /// <param name="dParentcode"></param>
    /// <returns></returns>
    public async Task<CommonResult> GetListd()
    {
      return await Task.Factory.StartNew(() =>
      {
        CommonResult result = new CommonResult();
        List<Dictionaries> dictionaries = new List<Dictionaries>();
        var list = baseApplication.mySqlSugar.QueryByExpression<Dictionaries>(
          o => o.status == 1,
          out var msg
        );
        if (string.IsNullOrEmpty(msg) && list != null && list.Count > 0)
        {
          dictionaries = list;
        }
        result.data = list;
        result.msg = msg;
        return result;
      });
    }

    /// <summary>
    /// 新增修改数据字典信息
    /// </summary>
    /// <param name="Dictionaries"></param>
    /// <returns></returns>
    public async Task<CommonResult> AddOrUpdate(Dictionaries info)
    {
      return await baseApplication.AddOrUpdate<Dictionaries>(
        info,
        BusinessType.dictionaries,
        BusinessLogType.writeLogToDataBase,
        null,
        (newid) =>
        {
          UserAuthorCache.AddDictionariescache(baseApplication.mySqlSugar, true, true);
        }
      );
    }

    /// <summary>
    /// 删除数据字典信息
    /// </summary>
    /// <param name="Id"></param>
    /// <param name="loginUserCode"></param>
    /// <param name="type"></param>
    /// <returns></returns>
    public async Task<CommonResult> Delete(string Id, string loginUserCode, string type)
    {
      return await baseApplication.Delete<Dictionaries>(
        Id,
        loginUserCode,
        type,
        BusinessType.dictionaries,
        (a, b, info) =>
        {
          return info.dName;
        },
        (db, info) =>
        {
          UserAuthorCache.AddDictionariescache(baseApplication.mySqlSugar, true, true);
        }
      );
    }

    /// <summary>
    /// 还原数据字典信息
    /// </summary>
    /// <param name="Id"></param>
    /// <param name="loginUserCode"></param>
    /// <returns></returns>
    public async Task<CommonResult> Reduction(string Id, string loginUserCode)
    {
      return await baseApplication.Reduction<Dictionaries>(
        Id,
        loginUserCode,
        BusinessType.dictionaries,
        (a, b, info) =>
        {
          return info.dName;
        },
        (db, info) =>
        {
          UserAuthorCache.AddDictionariescache(baseApplication.mySqlSugar, true, true);
        }
      );
    }
  }
}
